package com.p2p.bill.dao.impl;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.p2p.bill.dao.BillDao;
import com.p2p.bill.po.Bill;
import com.p2p.bill.vo.BillSellect;
import com.p2p.bill.vo.BillUpdate;
import com.p2p.common.redis.RedisService;
import com.p2p.common.redis.vo.RedisVo;
import com.p2p.daily.po.P2pDailyOutput;

@Repository
public class BillDaoImpl implements BillDao {
	@Resource(name = "redisService")
	private RedisService<RedisVo> redisService;
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Override
	public void putBill(String date_time) {
		String sql = "SELECT * FROM  `p2p_daily_output` WHERE STATUS = 1 AND date_time='" + date_time.substring(0, 10)
				+ " 00:00:00' ";

		List list = jdbcTemplate.queryForList(sql);

		String agentsql = "SELECT agent_code,tow_level_commission_rate FROM  `agent` WHERE STATUS=1";

		List agentlist = jdbcTemplate.queryForList(agentsql);

		String macsql = "SELECT agent_id,COUNT(outernet_ip),SUM(valid_submit_count),SUM(terminal_error_count) FROM `p2p_ip_"
				+ date_time.substring(0, 7).replaceAll("-", "") + "` where date_time='" + date_time
				+ "' GROUP BY date_time,agent_id,coin_type";

		List maclist = jdbcTemplate.queryForList(macsql);
		Map<String, Map> macmap = new HashMap<String, Map>();
		for (int i = 0; i < maclist.size(); i++) {

			Map maclistmap = (Map) maclist.get(i);
			macmap.put(maclistmap.get("agent_id").toString(), maclistmap);

		}

		StringBuffer addmessage = new StringBuffer();
		addmessage.append(
				"insert into bill (agentid,coin_type,sum,status,coin_price,ipcount,maccount,two_commission,errorcount,create_time,update_time) values");
		for (int i = 0; i < list.size(); i++) {
			Map map = (Map) list.get(i);
			BigDecimal sum = (BigDecimal) (map.get("predict_income"));
			String coinType = map.get("coin_type").toString();
			for (int a = 0; a < agentlist.size(); a++) {
				Map<String, String> agentmap = (Map) agentlist.get(a);
				String agent = agentmap.get("agent_code");
				String create_time = map.get("date_time").toString();
				String update_time = map.get("update_time").toString();
				String twocommission = agentmap.get("tow_level_commission_rate");
				BigDecimal coinPrice = (BigDecimal) (map.get("day_price"));
				BigDecimal icoinPrice = coinPrice.setScale(2, BigDecimal.ROUND_HALF_DOWN);
				int ipcount = 0;
				int maccount = 0;
				int errorcount = 0;
				if (macmap.get(agent) != null) {
					ipcount = Integer.valueOf(macmap.get(agent).get("COUNT(outernet_ip)").toString());
					errorcount = Integer.valueOf(macmap.get(agent).get("SUM(terminal_error_count)").toString());
					maccount = Integer.valueOf(macmap.get(agent).get("SUM(valid_submit_count)").toString());
				}

				String f;
				if (redisService.get("p2p-percent:" + date_time + ":" + agent + ":" + coinType) == null) {
					f = "0";
				} else {
					f = redisService.get("p2p-percent:" + date_time + ":" + agent + ":" + coinType).getValue();
				}

				BigDecimal b = new BigDecimal(f);
				System.out.println("Redis结果" + "p2p-percent:" + date_time + ":" + agent + ":" + coinType);
				BigDecimal decimal = b.multiply(sum);

				BigDecimal setScale = decimal.setScale(2, BigDecimal.ROUND_HALF_DOWN);

				addmessage.append("(" + agent + ",'" + coinType + "'," + setScale + ",0,'" + icoinPrice + "'," + ipcount
						+ "," + maccount + "," + twocommission + "," + errorcount + ",'" + create_time.substring(0, 10)
						+ "','" + update_time + "'),");
			}
		}
		String insertsql = addmessage.toString().substring(0, addmessage.toString().length() - 1);
		jdbcTemplate.execute(insertsql);
	}

	@Override
	public List<BillSellect> getBill(String agentid, String date_time) {
		RowMapper<BillSellect> rowMapper = new BeanPropertyRowMapper<>(BillSellect.class);

		String time = date_time;
		if (date_time.equals("")) {
			Date date = new Date();
			Date date1 = new Date(date.getTime() - 24 * 60 * 60 * 1000);
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			time = df.format(date1);
		}
		String sql = "SELECT *FROM `bill` WHERE agentid=" + agentid + " and create_time='" + time + "'";
		// String sql = "SELECT *FROM `bill` WHERE agentid=" + agentid + " AND
		// date_time='" + date_time + "'";
		System.out.println(sql);
		if (agentid.equals("agentid")) {
			agentid = "agent_code";
		}
		String agentsql = "SELECT agent_code FROM  `agent` WHERE STATUS=1 AND agent_code= " + agentid;
		List<BillSellect> list = jdbcTemplate.query(sql, rowMapper);
		List agentlist = jdbcTemplate.queryForList(agentsql);

		Map<Integer, BillSellect> map = new HashMap<Integer, BillSellect>();

		for (int i = 0; i < list.size(); i++) {

			if (map.containsKey(list.get(i).getAgentid())) {

				BillSellect bill = map.get(list.get(i).getAgentid());
				if (list.get(i).getCoinType().equals("ZEC")) {
					bill.setZECSUM(list.get(i).getSum());
					bill.setOtherPrice(list.get(i).getCoinPrice());
					map.put(list.get(i).getAgentid(), bill);
				} else {
					bill.setXZCSUM(list.get(i).getSum());
					bill.setOtherPrice(list.get(i).getCoinPrice());
					map.put(list.get(i).getAgentid(), bill);

				}

			} else {
				map.put(list.get(i).getAgentid(), list.get(i));
			}
		}
		List<BillSellect> alllist = new ArrayList<BillSellect>();
		for (int a = 0; a < agentlist.size(); a++) {
			Map amap = (Map) agentlist.get(a);
			if (map.get(Integer.valueOf(amap.get("agent_code").toString())) == null) {
				BillSellect bill = new BillSellect();
				bill.setAgentid(Integer.valueOf(amap.get("agent_code").toString()));
				alllist.add(bill);
			} else {
				alllist.add(map.get(Integer.valueOf(amap.get("agent_code").toString())));

			}

		}

		return alllist;
	}

	@Override
	public void updateBill(P2pDailyOutput p2pDailyOutput) {
		RowMapper<Bill> rowMapper = new BeanPropertyRowMapper<>(Bill.class);
		BigDecimal coin_price = p2pDailyOutput.getDayPrice();
		BigDecimal setScale = coin_price.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		BigDecimal sum = p2pDailyOutput.getPredictIncome();

		BigDecimal setsum = sum.setScale(2, BigDecimal.ROUND_HALF_DOWN);
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat dftime = new SimpleDateFormat("yyyy-MM-dd 23:00:00");

		String ssql = "select *from bill WHERE create_time = '" + df.format(p2pDailyOutput.getRecentSubmitTime())
				+ "' AND coin_type='" + p2pDailyOutput.getCoinType() + "'";
		System.out.println(ssql);
		List<Bill> list = jdbcTemplate.query(ssql, rowMapper);
		for (int i = 0; i < list.size(); i++) {
			String date_time = dftime.format(p2pDailyOutput.getDateTime());

			String f;
			if (redisService.get("p2p-percent:" + date_time + ":" + list.get(i).getAgentid() + ":"
					+ p2pDailyOutput.getCoinType()) == null) {
				f = "0";
			} else {
				f = redisService.get("p2p-percent:" + date_time + ":" + list.get(i).getAgentid() + ":"
						+ p2pDailyOutput.getCoinType()).getValue();
			}

			BigDecimal b = new BigDecimal(f);
			BigDecimal decimal = b.multiply(sum);

			BigDecimal summm = decimal.setScale(2, BigDecimal.ROUND_HALF_DOWN);
			String sql = "UPDATE bill SET coin_price =" + setScale + ", SUM=" + summm + " WHERE create_time = '"
					+ df.format(p2pDailyOutput.getRecentSubmitTime()) + "' AND coin_type='"
					+ p2pDailyOutput.getCoinType() + "' AND agentid=" + list.get(i).getAgentid();
			jdbcTemplate.execute(sql);
			System.out.println(sql);
		}

	}

	@Override
	public void updateAllBill(List<BillUpdate> list) {

		for (int i = 0; i < list.size(); i++) {

			BillUpdate billUpdate = list.get(i);
			String sql = "UPDATE bill SET commission =" + billUpdate.getCommission() + ", status=1 WHERE create_time = '"
					+ billUpdate.getTime() + "' AND agentid=" + list.get(i).getAgentid();
			System.out.println(sql);
			jdbcTemplate.execute(sql);
		}

	}

	@Override
	public void updateRelease(List<BillUpdate> list) {

		for (int i = 0; i < list.size(); i++) {

			BillUpdate billUpdate = list.get(i);
			String sql = "UPDATE bill SET status=2 WHERE create_time = '"
					+ billUpdate.getTime() + "' AND agentid=" + list.get(i).getAgentid();
			System.out.println(sql);
			jdbcTemplate.execute(sql);
		}

	}
}
